/**
 * 
 */
package br.pucpr.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import br.pucpr.view.TelaPrincipal;

/**
 * @author Thiago
 * 
 */
public class ServerCliente extends Thread {

	private Socket socket;
	private BufferedInputStream in;
	private TelaPrincipal tela;
	public boolean leu;
	private int porta;

	public ServerCliente(TelaPrincipal telaPrincipal, int porta) {
		tela = telaPrincipal;
		leu = false;
		this.porta = porta;
	}

	@SuppressWarnings("static-access")
	public void run() {

		ServerSocket serverSocket = null;

		try {
			serverSocket = new ServerSocket(porta);
		} catch (IOException e) {
			System.out.println("Nao consegui ouvir a porta: " + porta + ", "
					+ e);
			System.exit(1);
		}

		System.out.println("Servidor cliente Incializado com Sucesso.");

		try {
			while (true) {

				socket = null;
				socket = serverSocket.accept();

				in = new BufferedInputStream(socket.getInputStream());

				byte[] buffer = new byte[1024 * 50];

				BufferedOutputStream out = new BufferedOutputStream(
						new FileOutputStream("listaJogadores.dat"));

				int len = 0;
				while ((len = in.read(buffer)) > 0) {
					out.write(buffer, 0, len);
					System.out.print("#");
					leu = true;
				}
				out.flush();
				out.close();

				if (leu) {
					tela.carregarListaClientesOnLine();
				}
			}

		} catch (Exception e) {
			System.err.println("IOException:  " + e);
			e.printStackTrace();
		} finally {
			try {
				if (socket != null) {
					socket.close();
				}
			} catch (IOException e) {
				System.err.println("IOException:  " + e);
			}
		}

	}

}
